<template>
  <div class="app-container">
    <!-- 返回按钮 -->
    <el-row class="mb8">
      <el-col :span="24">
        <el-button icon="el-icon-back" size="small" @click="goBack">返回</el-button>
        <el-button type="primary" size="small" @click="handleSave" :loading="saveLoading">保存</el-button>
        <el-button type="success" size="small" @click="handleSubmit" :loading="submitLoading">提交验收</el-button>
      </el-col>
    </el-row>

    <!-- 任务信息 -->
    <el-card class="mb8">
      <div slot="header" class="card-header">
        <span class="card-title">验收任务 - {{ taskDetail.taskNo }}</span>
        <el-tag :type="getStatusTag(taskDetail.taskStatus)" size="medium">
          {{ getStatusText(taskDetail.taskStatus) }}
        </el-tag>
      </div>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-descriptions :column="1" size="small">
            <el-descriptions-item label="收货单号">{{ taskDetail.receiveOrderNo }}</el-descriptions-item>
            <el-descriptions-item label="供应商">{{ taskDetail.supplierName }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="8">
          <el-descriptions :column="1" size="small">
            <el-descriptions-item label="验收类型">{{ getInspectTypeText(taskDetail.inspectType) }}</el-descriptions-item>
            <el-descriptions-item label="总行数">{{ taskDetail.totalLines }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="8">
          <div class="progress-summary">
            <div class="progress-item">
              <span class="label">验收进度：</span>
              <el-progress :percentage="getProgress()" :stroke-width="8" class="progress-bar"></el-progress>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 验收操作区 -->
    <el-card>
      <div slot="header" class="card-header">
        <span class="card-title">验收明细操作</span>
        <div class="card-actions">
          <el-button size="small" @click="handleBatchQualified">批量合格</el-button>
          <el-button size="small" @click="handleBatchUnqualified">批量不合格</el-button>
          <el-button size="small" @click="handleAutoAssignLocation">自动分配货位</el-button>
        </div>
      </div>
      
      <!-- 验收明细表格 -->
      <el-table 
        :data="inspectDetails" 
        border 
        stripe 
        @selection-change="handleSelectionChange"
        :row-class-name="getRowClassName">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="商品信息" width="300">
          <template slot-scope="scope">
            <div class="product-info">
              <div class="product-name">{{ scope.row.productName }}</div>
              <div class="product-code">编码：{{ scope.row.productCode }}</div>
              <div class="product-spec">规格：{{ scope.row.specification || '-' }}</div>
            </div>
          </template>
        </el-table-column>  
      <el-table-column label="批次号" width="120">
          <template slot-scope="scope">
            <el-input 
              v-model="scope.row.batchCode" 
              size="small" 
              placeholder="请输入批次号"
              @change="handleBatchCodeChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="收货数量" prop="receiveQuantity" width="100" align="center" />
        <el-table-column label="验收数量" width="120">
          <template slot-scope="scope">
            <el-input-number 
              v-model="scope.row.inspectQuantity" 
              :min="0" 
              :max="scope.row.receiveQuantity" 
              size="small" 
              controls-position="right"
              @change="handleInspectQtyChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="合格数量" width="120">
          <template slot-scope="scope">
            <el-input-number 
              v-model="scope.row.qualifiedQuantity" 
              :min="0" 
              :max="scope.row.inspectQuantity" 
              size="small" 
              controls-position="right"
              @change="handleQualifiedQtyChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="不合格数量" prop="unqualifiedQuantity" width="100" align="center">
          <template slot-scope="scope">
            <span :style="{ color: scope.row.unqualifiedQuantity > 0 ? '#F56C6C' : '' }">
              {{ scope.row.unqualifiedQuantity || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="验收结果" width="120">
          <template slot-scope="scope">
            <el-select v-model="scope.row.inspectResult" size="small" @change="handleResultChange(scope.row)">
              <el-option label="合格" value="qualified" />
              <el-option label="不合格" value="unqualified" />
              <el-option label="部分合格" value="partial" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="货位选择" width="150">
          <template slot-scope="scope">
            <el-select 
              v-model="scope.row.shelfCode" 
              size="small" 
              placeholder="选择货位" 
              filterable
              @change="handleShelfChange(scope.row, $event)">
              <el-option 
                v-for="shelf in getAvailableShelves(scope.row)" 
                :key="shelf.shelfCode" 
                :label="shelf.shelfName" 
                :value="shelf.shelfCode">
                <span style="float: left">{{ shelf.shelfName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ shelf.availableCapacity }}%</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="异常处理" width="120">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.unqualifiedQuantity > 0" 
              type="text" 
              size="small" 
              @click="handleException(scope.row)">
              处理异常
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150">
          <template slot-scope="scope">
            <el-input 
              v-model="scope.row.remark" 
              size="small" 
              placeholder="备注信息"
              type="textarea"
              :rows="1" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 异常处理对话框 -->
    <el-dialog title="异常处理" :visible.sync="exceptionDialogVisible" width="600px" append-to-body>
      <el-form ref="exceptionForm" :model="exceptionForm" :rules="exceptionRules" label-width="100px">
        <el-form-item label="商品信息">
          <span>{{ exceptionForm.productName }} ({{ exceptionForm.productCode }})</span>
        </el-form-item>
        <el-form-item label="异常类型" prop="exceptionType">
          <el-select v-model="exceptionForm.exceptionType" placeholder="请选择异常类型">
            <el-option label="质量问题" value="quality" />
            <el-option label="数量不符" value="quantity" />
            <el-option label="包装破损" value="package" />
            <el-option label="规格不符" value="specification" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常描述" prop="exceptionDescription">
          <el-input 
            v-model="exceptionForm.exceptionDescription" 
            type="textarea" 
            :rows="3" 
            placeholder="请详细描述异常情况" />
        </el-form-item>
        <el-form-item label="处理方式" prop="handleMethod">
          <el-select v-model="exceptionForm.handleMethod" placeholder="请选择处理方式">
            <el-option label="退货" value="return" />
            <el-option label="换货" value="exchange" />
            <el-option label="降级处理" value="downgrade" />
            <el-option label="报废" value="scrap" />
            <el-option label="待定" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="责任方" prop="responsibleParty">
          <el-select v-model="exceptionForm.responsibleParty" placeholder="请选择责任方">
            <el-option label="供应商" value="supplier" />
            <el-option label="物流公司" value="logistics" />
            <el-option label="仓库" value="warehouse" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exceptionDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitException">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template><
script>
import { 
  getInspectTask, 
  getReceiveDetailForInspect, 
  getShelfInfoByProduct, 
  submitInspect,
  batchUpdateInspectDetails 
} from '@/api/wms/inspect'

export default {
  name: 'InspectOperation',
  data() {
    return {
      loading: false,
      saveLoading: false,
      submitLoading: false,
      taskId: null,
      taskDetail: {},
      inspectDetails: [],
      selectedRows: [],
      shelfList: [],
      
      // 异常处理
      exceptionDialogVisible: false,
      exceptionForm: {
        productId: null,
        productName: '',
        productCode: '',
        exceptionType: '',
        exceptionDescription: '',
        handleMethod: '',
        responsibleParty: ''
      },
      exceptionRules: {
        exceptionType: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
        exceptionDescription: [{ required: true, message: '请输入异常描述', trigger: 'blur' }],
        handleMethod: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
        responsibleParty: [{ required: true, message: '请选择责任方', trigger: 'change' }]
      }
    }
  },
  created() {
    this.taskId = this.$route.query.taskId
    if (this.taskId) {
      this.getTaskDetail()
    }
  },
  methods: {
    // 获取任务详情
    getTaskDetail() {
      this.loading = true
      getInspectTask(this.taskId).then(response => {
        this.taskDetail = response.data
        this.inspectDetails = response.data.details || []
        this.loadShelfInfo()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // 加载货位信息
    loadShelfInfo() {
      getShelfInfoByProduct('').then(response => {
        this.shelfList = response.data.shelfList || []
      })
    },

    // 返回
    goBack() {
      this.$router.go(-1)
    },

    // 保存
    handleSave() {
      this.saveLoading = true
      batchUpdateInspectDetails(this.inspectDetails).then(() => {
        this.$message.success('保存成功')
        this.saveLoading = false
      }).catch(() => {
        this.saveLoading = false
      })
    },

    // 提交验收
    handleSubmit() {
      // 验证必填项
      const invalidItems = this.inspectDetails.filter(item => 
        !item.batchCode || !item.shelfCode || item.inspectQuantity === null
      )
      
      if (invalidItems.length > 0) {
        this.$message.warning('请完善所有商品的批次号、货位和验收数量')
        return
      }

      this.$confirm('确认提交验收结果?', '提示', { type: 'warning' }).then(() => {
        this.submitLoading = true
        const data = {
          taskId: this.taskId,
          details: this.inspectDetails
        }
        
        submitInspect(data).then(() => {
          this.$message.success('验收提交成功')
          this.submitLoading = false
          this.$router.push('/wms/inspect')
        }).catch(() => {
          this.submitLoading = false
        })
      })
    },

    // 多选变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 批量合格
    handleBatchQualified() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要操作的行')
        return
      }
      
      this.selectedRows.forEach(row => {
        row.qualifiedQuantity = row.inspectQuantity
        row.unqualifiedQuantity = 0
        row.inspectResult = 'qualified'
      })
      this.$message.success('批量设置合格成功')
    },

    // 批量不合格
    handleBatchUnqualified() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要操作的行')
        return
      }
      
      this.selectedRows.forEach(row => {
        row.qualifiedQuantity = 0
        row.unqualifiedQuantity = row.inspectQuantity
        row.inspectResult = 'unqualified'
      })
      this.$message.success('批量设置不合格成功')
    },

    // 自动分配货位
    handleAutoAssignLocation() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择要操作的行')
        return
      }
      
      this.selectedRows.forEach(row => {
        const availableShelves = this.getAvailableShelves(row)
        if (availableShelves.length > 0) {
          const bestShelf = availableShelves[0] // 选择第一个可用货位
          row.shelfCode = bestShelf.shelfCode
          row.shelfName = bestShelf.shelfName
        }
      })
      this.$message.success('自动分配货位成功')
    },

    // 批次号变化
    handleBatchCodeChange(row) {
      // 可以在这里添加批次号验证逻辑
    },

    // 验收数量变化
    handleInspectQtyChange(row) {
      if (row.qualifiedQuantity > row.inspectQuantity) {
        row.qualifiedQuantity = row.inspectQuantity
      }
      row.unqualifiedQuantity = row.inspectQuantity - row.qualifiedQuantity
      this.updateInspectResult(row)
    },

    // 合格数量变化
    handleQualifiedQtyChange(row) {
      row.unqualifiedQuantity = row.inspectQuantity - row.qualifiedQuantity
      this.updateInspectResult(row)
    },

    // 更新验收结果
    updateInspectResult(row) {
      if (row.unqualifiedQuantity === 0) {
        row.inspectResult = 'qualified'
      } else if (row.qualifiedQuantity === 0) {
        row.inspectResult = 'unqualified'
      } else {
        row.inspectResult = 'partial'
      }
    },

    // 验收结果变化
    handleResultChange(row) {
      if (row.inspectResult === 'qualified') {
        row.qualifiedQuantity = row.inspectQuantity
        row.unqualifiedQuantity = 0
      } else if (row.inspectResult === 'unqualified') {
        row.qualifiedQuantity = 0
        row.unqualifiedQuantity = row.inspectQuantity
      }
    },

    // 货位变化
    handleShelfChange(row, shelfCode) {
      const shelf = this.shelfList.find(s => s.shelfCode === shelfCode)
      if (shelf) {
        row.shelfName = shelf.shelfName
      }
    },

    // 获取可用货位
    getAvailableShelves(row) {
      // 这里可以根据商品特性筛选合适的货位
      return this.shelfList.filter(shelf => shelf.availableCapacity > 10)
    },

    // 处理异常
    handleException(row) {
      this.exceptionForm = {
        productId: row.productId,
        productName: row.productName,
        productCode: row.productCode,
        exceptionType: '',
        exceptionDescription: '',
        handleMethod: '',
        responsibleParty: ''
      }
      this.exceptionDialogVisible = true
    },

    // 提交异常处理
    submitException() {
      this.$refs.exceptionForm.validate(valid => {
        if (valid) {
          // 这里可以调用异常处理API
          this.$message.success('异常处理记录已提交')
          this.exceptionDialogVisible = false
        }
      })
    },

    // 获取行样式
    getRowClassName({ row }) {
      if (row.unqualifiedQuantity > 0) {
        return 'warning-row'
      }
      if (row.inspectResult === 'qualified') {
        return 'success-row'
      }
      return ''
    },

    // 获取进度
    getProgress() {
      if (!this.taskDetail.totalLines || this.taskDetail.totalLines === 0) return 0
      const inspectedCount = this.inspectDetails.filter(item => item.inspectResult).length
      return Math.round(inspectedCount / this.taskDetail.totalLines * 100)
    },

    // 获取状态标签类型
    getStatusTag(status) {
      return { 'pending': 'info', 'in_progress': 'warning', 'completed': 'success' }[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      return { 'pending': '待验收', 'in_progress': '验收中', 'completed': '已完成' }[status] || status
    },

    // 获取验收类型文本
    getInspectTypeText(type) {
      return { 'full': '全检', 'sample': '抽检', 'skip': '免检' }[type] || type
    }
  }
}
</script><st
yle scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 10px;
}

.progress-summary {
  padding: 10px 0;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar {
  flex: 1;
}

.product-info {
  line-height: 1.4;
}

.product-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 2px;
}

.product-code, .product-spec {
  font-size: 12px;
  color: #909399;
  margin-bottom: 1px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 表格行样式 */
.el-table .warning-row {
  background: #fdf6ec;
}

.el-table .success-row {
  background: #f0f9ff;
}

/* 异常处理对话框样式 */
.dialog-footer {
  text-align: right;
}
</style>